/* eslint-env mocha */
const fs = require('fs')
const path = require('path')
const assert = require('assert')
const { exec } = require('child_process')
const cfg = require('../lib/config')

describe('Keepfast', () => {
  const projects = ['vue-simple', 'vue-large-entrypoint']
  const fixturesDir = path.resolve(__dirname, 'fixtures')

  describe('configuration', () => {
    const file = path.join(fixturesDir, cfg.filename)
    const jsonFile = path.resolve(fixturesDir, 'keepfast.config.json')

    it('should be successfully created by the `keepfast init` command', function (done) {
      this.timeout(3000)
      exec('keepfast init', { cwd: fixturesDir }, (err) => {
        if (fs.existsSync(file)) {
          const config = require(file)
          assert.equal(!err && config.repository.name === 'example', true)
          fs.unlinkSync(file)
        }
        done()
      })
    })

    fs.writeFileSync(jsonFile, JSON.stringify({
      repository: {
        owner: 'gitee-frontend',
        name: 'keepfast'
      },
      build: null,
      lighthouse: {
        pagePath: 'home'
      }
    }, null, 2))

    const config = cfg.load(jsonFile)

    it('should merge the default configuration recursively', () => {
      assert.strictEqual(config.repository.name, 'keepfast')
      assert.strictEqual(config.lighthouse.tool, 'vue-cli-service')
      assert.strictEqual(config.lighthouse.pagePath, 'home')
    })
    it('should support setting property to null', () => {
      assert.strictEqual(config.build, null)
    })
    fs.unlinkSync(jsonFile)
  })
  projects.forEach((project) => {
    describe(project, () => {
      const cwd = path.resolve(__dirname, 'fixtures', project)
      const reportPath = path.resolve(cwd, 'report.json')

      if (fs.existsSync(reportPath)) {
        fs.unlinkSync(reportPath)
      }
      it('should upload message by --use-message option', function (done) {
        this.timeout(10000)
        exec(`keepfast upload --use-message "已开始分析项目：${project}"`, { cwd }, (err) => {
          assert.equal(!err, true)
          done()
        })
      })
      it('should generate report.json', function (done) {
        this.timeout(10 * 60 * 1000)

        exec('npm install', { cwd }, () => {
          exec(`keepfast report ${reportPath}`, { cwd }, () => {
            assert.equal(fs.existsSync(reportPath), true)
            done()
          })
        })
      })
      it('should upload report.json', function (done) {
        this.timeout(10 * 60 * 1000)
        exec(`keepfast upload ${reportPath}`, { cwd }, (err) => {
          assert.equal(!err, true)
          done()
        })
      })
    })
  })
})
